package network.server.handler.StoreHandler;

import common.model.Entity.StoreEntity.Product;
import module.StoreService.ProductService;
import module.StoreService.Impl.ProductServiceImpl;
import network.protocol.Request;
import network.protocol.Response;
import network.server.RequestHandler;

import java.util.Map;
import java.util.Optional;

/**
 * {@code ProductHandler} 是商品相关请求的处理器，实现了 {@link RequestHandler} 接口。
 * <p>
 * 主要职责：
 * <ul>
 *     <li>接收并解析客户端请求</li>
 *     <li>调用 {@link ProductService} 执行商品相关的业务逻辑</li>
 *     <li>返回统一的 {@link Response} 对象</li>
 * </ul>
 *
 * 支持的操作：
 * <ul>
 *     <li>{@code getProductById} - 根据商品 ID 获取商品</li>
 *     <li>{@code getProductByName} - 根据商品名称获取商品</li>
 *     <li>{@code getAllProducts} - 获取所有商品</li>
 *     <li>{@code getProductsByCategoryId} - 根据分类 ID 获取商品</li>
 *     <li>{@code getProductsByCategoryName} - 根据分类名称获取商品</li>
 *     <li>{@code createProduct} - 创建商品</li>
 *     <li>{@code updateProduct} - 更新商品</li>
 *     <li>{@code deleteProduct} - 删除商品</li>
 *     <li>{@code getProductCount} - 获取商品总数</li>
 *     <li>{@code productExists} - 检查商品是否存在</li>
 *     <li>{@code productNameExists} - 检查商品名称是否存在</li>
 *     <li>{@code updateProductStock} - 更新商品库存</li>
 *     <li>{@code updateProductStatus} - 更新商品状态（上下架）</li>
 * </ul>
 */
public class ProductHandler implements RequestHandler {
    private final ProductService productService;

    /**
     * 构造函数，使用单例模式获取 {@link ProductService} 实例。
     */
    public ProductHandler() {
        this.productService = ProductServiceImpl.getInstance();
    }

    /**
     * 处理客户端请求，根据 action 动态调用对应的商品操作。
     *
     * @param req 请求对象，包含 action 和参数
     * @return 响应对象，包含执行结果或错误信息
     */
    @Override
    public Response<?> handle(Request req) {
        String action = req.getAction();
        String methodName = action.substring(action.indexOf('.') + 1);
        Map<String, Object> params = req.getParams();

        try {
            switch (methodName) {
                case "getProductById":
                    return handleGetProductById(params);
                case "getProductByName":
                    return handleGetProductByName(params);
                case "getAllProducts":
                    return productService.getAllProducts();
                case "getProductsByCategoryId":
                    return handleGetProductsByCategoryId(params);
                case "getProductsByCategoryName":
                    return handleGetProductsByCategoryName(params);
                case "createProduct":
                    return handleCreateProduct(params);
                case "updateProduct":
                    return handleUpdateProduct(params);
                case "deleteProduct":
                    return handleDeleteProduct(params);
                case "getProductCount":
                    return productService.getProductCount();
                case "productExists":
                    return handleProductExists(params);
                case "productNameExists":
                    return handleProductNameExists(params);
                case "updateProductStock":
                    return handleUpdateProductStock(params);
                case "updateProductStatus":
                    return handleUpdateProductStatus(params);
                default:
                    return Response.error("未知操作: " + methodName);
            }
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误: " + e.getMessage());
        } catch (Exception e) {
            return Response.error("处理请求时发生错误: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取商品
     *
     * @param params 参数，必须包含 {@code id}
     * @return 商品信息或错误信息
     */
    private Response<?> handleGetProductById(Map<String, Object> params) {
        if (!params.containsKey("id")) {
            return Response.error("缺少必要参数: id");
        }

        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());
            return productService.getProductById(id);
        } catch (NumberFormatException e) {
            return Response.error("id参数格式错误");
        }
    }

    /**
     * 根据名称获取商品
     *
     * @param params 参数，必须包含 {@code name}
     * @return 商品信息或错误信息
     */
    private Response<?> handleGetProductByName(Map<String, Object> params) {
        if (!params.containsKey("name")) {
            return Response.error("缺少必要参数: name");
        }

        Object nameObj = params.get("name");
        if (nameObj == null) {
            return Response.error("name参数不能为null");
        }
        String name = nameObj.toString();
        return productService.getProductByName(name);
    }

    /**
     * 根据分类ID获取商品
     *
     * @param params 参数，必须包含 {@code categoryId}
     * @return 商品列表或错误信息
     */
    private Response<?> handleGetProductsByCategoryId(Map<String, Object> params) {
        if (!params.containsKey("categoryId")) {
            return Response.error("缺少必要参数: categoryId");
        }

        try {
            Object categoryIdObj = params.get("categoryId");
            if (categoryIdObj == null) {
                return Response.error("categoryId参数不能为null");
            }
            long categoryId = Long.parseLong(categoryIdObj.toString());
            return productService.getProductsByCategoryId(categoryId);
        } catch (NumberFormatException e) {
            return Response.error("categoryId参数格式错误");
        }
    }

    /**
     * 根据分类名称获取商品
     *
     * @param params 参数，必须包含 {@code categoryName}
     * @return 商品列表或错误信息
     */
    private Response<?> handleGetProductsByCategoryName(Map<String, Object> params) {
        if (!params.containsKey("categoryName")) {
            return Response.error("缺少必要参数: categoryName");
        }

        Object categoryNameObj = params.get("categoryName");
        if (categoryNameObj == null) {
            return Response.error("categoryName参数不能为null");
        }
        String categoryName = categoryNameObj.toString();
        return productService.getProductsByCategoryName(categoryName);
    }

    /**
     * 创建商品
     *
     * @param params 参数，必须包含 {@code productName}, {@code price}, {@code stock}, {@code categoryName}
     *               可选参数：{@code description}, {@code status}, {@code imageUrl}
     * @return 创建结果
     */
    private Response<?> handleCreateProduct(Map<String, Object> params) {
        if (!params.containsKey("productName") || !params.containsKey("price") ||
                !params.containsKey("stock") || !params.containsKey("categoryName")) {
            return Response.error("缺少必要参数: productName，categoryName，price，stock");
        }

        try {
            Product product = new Product();

            Object productNameObj = params.get("productName");
            if (productNameObj == null) {
                return Response.error("productName参数不能为null");
            }
            product.setProductName(productNameObj.toString());

            Object priceObj = params.get("price");
            if (priceObj == null) {
                return Response.error("price参数不能为null");
            }
            product.setPrice(Double.parseDouble(priceObj.toString()));

            Object stockObj = params.get("stock");
            if (stockObj == null) {
                return Response.error("stock参数不能为null");
            }
            product.setStock(Integer.parseInt(stockObj.toString()));

            Object categoryNameObj = params.get("categoryName");
            if (categoryNameObj == null) {
                return Response.error("categoryName参数不能为null");
            }
            product.setCategoryName(categoryNameObj.toString());

            if (params.containsKey("description")) {
                Object descriptionObj = params.get("description");
                if (descriptionObj != null) {
                    product.setDescription(descriptionObj.toString());
                }
            }

            if (params.containsKey("status")) {
                Object statusObj = params.get("status");
                if (statusObj != null) {
                    product.setStatus(Integer.parseInt(statusObj.toString()));
                } else {
                    product.setStatus(1);
                }
            } else {
                product.setStatus(1);
            }

            if (params.containsKey("imageUrl")) {
                Object imageUrlObj = params.get("imageUrl");
                if (imageUrlObj != null) {
                    product.setImageUrl(imageUrlObj.toString());
                }
            }

            return productService.createProduct(product);
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误");
        }
    }

    /**
     * 更新商品
     *
     * @param params 参数，必须包含 {@code id}，可选参数：{@code productName}, {@code price}, {@code stock}, {@code description}, {@code status}, {@code imageUrl}
     * @return 更新结果
     */
    private Response<?> handleUpdateProduct(Map<String, Object> params) {
        if (!params.containsKey("id")) {
            return Response.error("缺少必要参数: id");
        }

        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());

            Response<Optional<Product>> response = productService.getProductById(id);
            if (!response.isSuccess() || response.getData().isEmpty()) {
                return Response.error("未找到指定商品");
            }

            Product product = response.getData().get();

            if (params.containsKey("productName")) {
                Object productNameObj = params.get("productName");
                if (productNameObj != null) {
                    product.setProductName(productNameObj.toString());
                }
            }

            if (params.containsKey("price")) {
                Object priceObj = params.get("price");
                if (priceObj != null) {
                    product.setPrice(Double.parseDouble(priceObj.toString()));
                }
            }

            if (params.containsKey("stock")) {
                Object stockObj = params.get("stock");
                if (stockObj != null) {
                    product.setStock(Integer.parseInt(stockObj.toString()));
                }
            }

            if (params.containsKey("description")) {
                Object descriptionObj = params.get("description");
                if (descriptionObj != null) {
                    product.setDescription(descriptionObj.toString());
                }
            }

            if (params.containsKey("status")) {
                Object statusObj = params.get("status");
                if (statusObj != null) {
                    product.setStatus(Integer.parseInt(statusObj.toString()));
                }
            }

            if (params.containsKey("imageUrl")) {
                Object imageUrlObj = params.get("imageUrl");
                if (imageUrlObj != null) {
                    product.setImageUrl(imageUrlObj.toString());
                }
            }

            return productService.updateProduct(product);
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误");
        }
    }

    /**
     * 删除商品
     *
     * @param params 参数，必须包含 {@code id}
     * @return 删除结果
     */
    private Response<?> handleDeleteProduct(Map<String, Object> params) {
        if (!params.containsKey("id")) {
            return Response.error("缺少必要参数: id");
        }

        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());
            return productService.deleteProduct(id);
        } catch (NumberFormatException e) {
            return Response.error("id参数格式错误");
        }
    }

    /**
     * 检查商品是否存在
     *
     * @param params 参数，必须包含 {@code id}
     * @return 是否存在
     */
    private Response<?> handleProductExists(Map<String, Object> params) {
        if (!params.containsKey("id")) {
            return Response.error("缺少必要参数: id");
        }

        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());
            return productService.productExists(id);
        } catch (NumberFormatException e) {
            return Response.error("id参数格式错误");
        }
    }

    /**
     * 检查商品名称是否存在
     *
     * @param params 参数，必须包含 {@code name}
     * @return 是否存在
     */
    private Response<?> handleProductNameExists(Map<String, Object> params) {
        if (!params.containsKey("name")) {
            return Response.error("缺少必要参数: name");
        }

        Object nameObj = params.get("name");
        if (nameObj == null) {
            return Response.error("name参数不能为null");
        }
        String name = nameObj.toString();
        return productService.productNameExists(name);
    }

    /**
     * 更新商品库存
     *
     * @param params 参数，必须包含 {@code id}, {@code stock}
     * @return 更新结果
     */
    private Response<?> handleUpdateProductStock(Map<String, Object> params) {
        if (!params.containsKey("id") || !params.containsKey("stock")) {
            return Response.error("缺少必要参数: id 或 stock");
        }

        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());

            Object stockObj = params.get("stock");
            if (stockObj == null) {
                return Response.error("stock参数不能为null");
            }
            int stock = Integer.parseInt(stockObj.toString());

            return productService.updateProductStock(id, stock);
        } catch (NumberFormatException e) {
            return Response.error("id或stock参数格式错误");
        }
    }

    /**
     * 更新商品状态（上架/下架）
     *
     * @param params 参数，必须包含 {@code id}, {@code status}
     * @return 更新结果
     */
    private Response<?> handleUpdateProductStatus(Map<String, Object> params) {
        if (!params.containsKey("id") || !params.containsKey("status")) {
            return Response.error("缺少必要参数: id 或 status");
        }

        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());

            Object statusObj = params.get("status");
            if (statusObj == null) {
                return Response.error("status参数不能为null");
            }
            int status = Integer.parseInt(statusObj.toString());

            return productService.updateProductStatus(id, status);
        } catch (NumberFormatException e) {
            return Response.error("id或status参数格式错误");
        }
    }
}
